package com.v0710.module.oss.service.handler;

import com.v0710.common.util.DateUtils;
import com.v0710.framework.exception.ServiceException;
import com.v0710.module.admin.entity.SysOss;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @description：本地文件上传处理器
 * @author：yufan.wang
 * @create：2024/1/5 20:42
 */
@Slf4j
@Component(value = "localFileStorageHandler")
public class LocalFileStorageHandler implements FileStorageHandler {

    @Value("${server.port:8080}")
    private int port;

    /**
     * 文件上传至阿里云
     *
     * @param file 文件
     * @return String
     */
    @Override
    public String uploadFile(MultipartFile file, SysOss sysOss) {

        if (file.isEmpty()) {
            log.error("the file to be uploaded is empty");
            throw new ServiceException("上传的文件是空的！");
        }

        try {
            //校验文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            //首次需生成目录
            String property = System.getProperty("user.dir")+"/localFile/";
            File folder = new File(property);
            if (!folder.exists()) {
                folder.mkdirs();
            }

            String fileName = DateUtils.getDate() + System.currentTimeMillis() + "." + suffix;
            String absolutePath = property + fileName;
            file.transferTo(new File(absolutePath));
            return "http://127.0.0.1:" + port + "/ossFile/" + fileName;

        } catch (Exception e) {
            log.error("the file upload error occurred. e ", e);
        }

        return null;
    }

}
